import 'dart:convert';

import 'package:dear_lottery/tools/DL_Config.dart';
import 'package:dear_lottery/tools/DL_drawNumbersView.dart';
import 'package:flutter/material.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:hexcolor/hexcolor.dart';
import 'package:intl/intl.dart';

import '../Results/DL_resultDetailPageVC.dart';
import '../tools/DL_Segment.dart';
import '../tools/models/DL_DataViewModel.dart';
import '../tools/models/DL_LottoModel.dart';
import '../tools/sqLite/EJ_myTicketEntity.dart';
import 'DL_checkerDetailPageVC.dart';
import 'ScanTicket/DL_scanTicketPageVC.dart';

class DL_CheckerPageVC extends StatefulWidget {
  DL_CheckerPageVC({
    super.key,
    this.pageController,
  });
  PageController? pageController;
  @override
  State<DL_CheckerPageVC> createState() => _DL_CheckerPageVCState();
}

class _DL_CheckerPageVCState extends State<DL_CheckerPageVC> {
  ///
  late var onePMModels = [];
  late var sixPMModels = [];
  late var eightPMModels = [];
  late var otherPMModels = [];

  int _currentTypeIndex = 0;
  late var _currentPMModels = [];

  late var _currentLottoModel = DL_LottoModel();
  late var _numbersMap = {}; //号码

  MyTicketEntity ticketEntity = MyTicketEntity.instan(); //数据库

  ///
  final ScrollController _scrollController = ScrollController();
  int _currentDayIndex = 0; //选中日期的下标
  ///
  var _days = [];
  late List _drawDates = []; //所有日期集合
  late List _datas = []; //列表数据源

  void _configData() {
    onePMModels = DL_DataViewModel().DL_onePM_resultsModels;
    sixPMModels = DL_DataViewModel().DL_sixPM_resultsModels;
    eightPMModels = DL_DataViewModel().DL_eightPM_resultsModels;
    otherPMModels = DL_DataViewModel().DL_others_resultsModels;
    _onTabChanged(_currentTypeIndex);
  }

  void _onTabChanged(int index) {
    switch (index) {
      case 0:
        _currentPMModels = onePMModels.reversed.toList();
        break;
      case 1:
        _currentPMModels = sixPMModels.reversed.toList();
        break;
      case 2:
        _currentPMModels = eightPMModels.reversed.toList();
        break;
      case 3:
        _currentPMModels = otherPMModels.reversed.toList();
        break;
      default:
    }

    _currentLottoModel = _currentPMModels.last;
    if (_currentLottoModel.first_prize_num!.isNotEmpty) {
      String firstPrizeNum = _currentLottoModel.first_prize_num![0];
      List<String> charArray = firstPrizeNum.split('');
      var balls = [];
      for (var i = 0; i < charArray.length; i++) {
        var ball = {
          'number': charArray[i],
          'isRight': false,
          'isNormal': true
        }; //isNormal代表是否对比中奖号码，true不用对比，false需要对比。isRight代表是否中奖号码
        balls.add(ball);
      }
      var title = '1st Prize';
      _numbersMap = {'title': title, 'balls': balls};
    }

    _drawDates.clear();
    for (DL_LottoModel model in _currentPMModels) {
      var date = model.draw_date;
      DateTime drawDateTimeUTC = DateTime.parse(date!);
      var month = DateFormat('MMM').format(drawDateTimeUTC);
      var day = DateFormat('dd').format(drawDateTimeUTC);
      var dateMap = {'month': month, 'day': day};
      _drawDates.add(dateMap);
    }

    _currentDayIndex = _drawDates.length - 1;

    setState(() {});

    ///
    Future.delayed(const Duration(milliseconds: 100), () {
      // _scrollController.jumpTo(_scrollController.position.maxScrollExtent);
      _scrollController.animateTo(_scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 200), curve: Curves.ease);
    });
  }

  _drawDateClick(int index) {
    _currentDayIndex = index;
    _currentLottoModel = _currentPMModels[index];
    if (_currentLottoModel.first_prize_num!.isNotEmpty) {
      String firstPrizeNum = _currentLottoModel.first_prize_num![0];
      List<String> charArray = firstPrizeNum.split('');
      var balls = [];
      for (var i = 0; i < charArray.length; i++) {
        var ball = {
          'number': charArray[i],
          'isRight': false,
          'isNormal': true
        }; //isNormal代表是否对比中奖号码，true不用对比，false需要对比。isRight代表是否中奖号码
        balls.add(ball);
      }
      var title = '1st Prize';
      _numbersMap = {'title': title, 'balls': balls};
    }

    setState(() {});
  }

  ///取出保存的ticket
  _getAllTicket() async {
    var result = await ticketEntity.find();
    // 处理查询结果
    // List<Map<String, dynamic>> resultList = result.toList();
    List resultList = result.toList();
    for (Map rowData in resultList) {
      // 处理每行数据

      var idStr = rowData['id'];
      var name = rowData['name'];
      var numbers = jsonDecode(rowData['numbers']);
      debugPrint('rowData-$rowData');
      var ticket = {"id": idStr, "name": "$name", "numbers": numbers};
      _datas.add(ticket);
    }
    debugPrint('_datas---$_datas');
    setState(() {});
  }

  ///
  _addTicket() {
    widget.pageController!.jumpToPage(2);
  }

  ///
  _scanTicket() {
    Navigator.of(context).push(
      MaterialPageRoute(
        builder: (context) => DL_ScanTicketVC(
          saveCallback: (int code) {
            if (code == 1) {
              //扫码成功
              _getAllTicket();
            }
          },
        ),
      ),
    );
  }

  bool compearMatchingElements(
      List<String> currentArray, List<String> subArray) {
    bool count = false;

    ///
    String cArr = currentArray.join('');
    String sArr = subArray.join('');
    if (cArr.length < sArr.length) {
      if (right(sArr, cArr.length) == cArr) {
        count = true;
      }
    } else {
      if (right(cArr, sArr.length) == sArr) {
        count = true;
      }
    }

    return count;
  }

  String right(String str, int length) {
    return str.substring(str.length - length);
  }

  ///
  void _goToDetailPage(var numbers) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) =>
                DL_CheckerDetailVC(myTicketNumbers: numbers)));
  }

  void _goToResultDetailPage(var model) {
    Navigator.push(
        context,
        MaterialPageRoute(
            builder: (context) => DL_ResultDetailPageVC(
                  lottoModel: model,
                )));
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();

    _configData();
    _getAllTicket();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Image.asset(
          'assets/sys_imgs/DearLottery Logo.png',
          width: 160,
          height: 50,
        ),
        backgroundColor: DL_Config.DL_MainColor,
        foregroundColor: Colors.white,
        centerTitle: true,
      ),
      body: Container(
        color: DL_Config.DL_pageBgColor,
        child: Column(
          children: [
            segmentView(),
            headerView(),
            bodyContentList(),
          ],
        ),
      ),
    );
  }

  Widget bodyContentList() {
    return Expanded(
      child: ListView.builder(
          // padding: const EdgeInsets.fromLTRB(15, 15, 15, 1),
          itemCount: _datas.length + 2,
          // itemCount: 3,
          itemBuilder: (BuildContext context, int index) {
            if (index == 0) {
              return ListHeaderText();
            } else if (index == (_datas.length + 2) - 1) {
              return ListFooterText();
            } else {
              int idx = index - 1;
              var data = _datas[idx];
              return cellSlidable(data, idx);
            }
          }),
    );
  }

  Widget cellSlidable(Map data, int index) {
    // var idStr = data['id'];
    return Padding(
      // key: ValueKey(index),
      padding: const EdgeInsets.only(top: 7.5, bottom: 7.5),
      child: Slidable(
        // controller: controller,
        // Specify a key if the Slidable is dismissible.
        // key: ValueKey(index),
        key: UniqueKey(),

        // The start action pane is the one at the left or the top side.
        startActionPane: ActionPane(
          // A motion is a widget used to control how the pane animates.
          motion: const ScrollMotion(),

          // A pane can dismiss the Slidable.
          dismissible: DismissiblePane(onDismissed: () {
            debugPrint('dismiss');
            // _deleteTicketWith(index, idStr);
          }),

          // All actions are defined in the children parameter.
          children: [
            // A SlidableAction can have an icon and/or a label.
            SlidableAction(
              // onPressed: doNothing(context, index, idStr),
              onPressed: (BuildContext context) {
                // doNothing(context, index, idStr);
              },
              backgroundColor: HexColor('#ff3433'),
              foregroundColor: Colors.white,
              icon: Icons.delete,
              borderRadius: const BorderRadius.all(Radius.circular(12)),
              // backgroundColor: Colors.orange,
              // flex: 1,
              label: 'Delete',
            ),
          ],
        ),
        // child: contentListCell(data, index),
        child: listCell(data, index),
      ),
    );
  }

  Widget listCell(Map data, int index) {
    var ticketName = data['name'];
    List numbers = data['numbers'];

    List<String> numbersList = [];
    numbersList = numbers.map((item) => item?.toString() ?? '').toList();

    var numbersMap = {};
    List<String> mostSimilar = [];
    bool bingo = false;

    var _prizeAmount = '';

    List allPrizes = _currentLottoModel.all_prize_num!;
    for (Map prizeMap in allPrizes) {
      List prizeNumbers = prizeMap['numbers'];
      for (String prizeNumber in prizeNumbers) {
        List<String> tNumberList = prizeNumber.split('');
        bingo = compearMatchingElements(numbersList, tNumberList);
        if (bingo) {
          mostSimilar = tNumberList;
          // _pModel = prizeModel;
          _prizeAmount = prizeMap['prizeAmount'];
          break;
        }
      }
    }

    ///
    List nums = [];
    nums.clear();
    for (var i = numbers.length - 1; i >= 0; i--) {
      String cNum = numbers[i];
      bool isRight = false;
      if (mostSimilar.isNotEmpty) {
        int numbersLength = numbers.length;
        int mostSimilarLength = mostSimilar.length;
        int idx = i - (numbersLength - mostSimilarLength);
        if (idx >= 0) {
          String rNum = mostSimilar[idx];
          if (cNum == rNum) {
            isRight = true;
          }
        }
      }
      var num = {
        'number': cNum,
        'isRight': isRight,
        'isNormal': false
      }; //isNormal代表是否对比中奖号码，true不用对比，false需要对比。isRight代表是否中奖号码
      nums.add(num);
    }

    var prize = '';
    var title = 'No Matched Prizes';
    if (mostSimilar.isNotEmpty) {
      prize = _prizeAmount;
      // prizeAmount = _pModel.prize_amount;
      _prizeAmount = _prizeAmount + ' INR';
      title = 'Matched $prize Prize';
    }

    numbersMap = {'title': title, 'balls': nums.reversed.toList()};

    return SizedBox(
      height: 140,
      child: GestureDetector(
        onTap: () {
          debugPrint('result');
          _goToDetailPage(nums.reversed.toList());
        },
        child: Container(
          margin: const EdgeInsets.fromLTRB(15, 0, 15, 1),
          decoration: const BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.all(Radius.circular(10)),
          ),
          child: Column(children: [
            Container(
              margin: const EdgeInsets.only(left: 10, right: 10),
              height: 40,
              // color: Colors.yellow,
              child: Row(children: [
                Text(ticketName,
                    style: const TextStyle(
                      fontWeight: FontWeight.w600,
                      fontSize: 13,
                      color: Colors.black,
                    )),
                const Spacer(),
                Text(
                  _prizeAmount,
                  style: TextStyle(
                      fontWeight: FontWeight.w700,
                      fontSize: 15,
                      color: HexColor('#D32F7D')),
                ),
              ]),
            ),
            Expanded(
                child: Container(
              width: double.infinity,
              child: Row(
                children: [
                  Expanded(
                      child: Container(
                    // color: Colors.red,
                    alignment: Alignment.centerLeft,
                    // child: KalDrawnumbersview(data: numbersMap),
                    child: drawingNumbersView(numbersMap),
                  )),
                  assetTagView(),
                ],
              ),
            )),
          ]),
        ),
      ),
    );
  }

  Widget drawingNumbersView(var data) {
    return Container(
      margin: const EdgeInsets.all(10),
      child: DL_drawNumbersView(data: data),
    );
  }

  Widget headerView() {
    return Column(children: [
      headerButtonView(),
      headerSwitchDayView(),
      Divider(height: 0.1, color: DL_Config.DL_MainColor), // 添加分割线
      headerFirstPrizeView(),
    ]);
  }

  Widget headerFirstPrizeView() {
    return GestureDetector(
      onTap: () {
        debugPrint('1st prize');
        _goToResultDetailPage(_currentLottoModel);
      },
      child: Container(
        color: Colors.white,
        padding: const EdgeInsets.only(top: 5, bottom: 1),
        child: Column(
          children: [
            // DL_drawNumbersView(data: _numbersMap),
            drawingNumbersView(_numbersMap),
            Container(
              alignment: Alignment.topCenter,
              // color: Colors.yellow,
              height: 25,
              child:
                  Row(mainAxisAlignment: MainAxisAlignment.center, children: [
                Text(
                  'Full Details',
                  style: TextStyle(color: HexColor('#666666'), fontSize: 10),
                ),
                Icon(Icons.arrow_right, color: HexColor('#666666'))
              ]),
            ),
          ],
        ),
      ),
    );
  }

  Widget headerSwitchDayView() {
    List days = _drawDates;

    return Container(
      height: 74,
      width: double.infinity,
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Padding(
            padding: EdgeInsets.only(left: 20),
            child: Text(
              'Choose the draw you want to check',
              style: TextStyle(
                fontSize: 13,
                fontWeight: FontWeight.w600,
                color: Colors.black,
              ),
            ),
          ),
          Expanded(
            child: ListView.builder(
              controller: _scrollController,
              scrollDirection: Axis.horizontal,
              itemCount: days.length,
              itemBuilder: (BuildContext context, int index) {
                // return days[index];
                return DateView(days[index], index);
              },
            ),
          ),
        ],
      ),
    );
  }

  Widget headerButtonView() {
    double btnH = 36.0;
    double btnW = 130.0;
    return Container(
      height: 60,
      color: Colors.white,
      child: Row(
        children: [
          Expanded(
            child: Container(
              // color: Colors.lightGreen,
              alignment: Alignment.center,
              child: Container(
                height: btnH,
                width: btnW,
                decoration: BoxDecoration(
                    color: DL_Config.DL_MainColor,
                    borderRadius:
                        BorderRadius.all(Radius.circular(btnH * 0.5))),
                child: TextButton(
                    onPressed: () {
                      debugPrint('Scan Ticket');
                      // _addTicket();
                      _scanTicket();
                    },
                    child: const Text(
                      'Scan Ticket',
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    )),
              ),
            ),
          ),
          Expanded(
            child: Container(
              alignment: Alignment.center,
              child: Container(
                height: btnH,
                width: btnW,
                decoration: BoxDecoration(
                    color: DL_Config.DL_MainColor,
                    borderRadius:
                        BorderRadius.all(Radius.circular(btnH * 0.5))),
                child: TextButton(
                    onPressed: () {
                      debugPrint('Add Ticket');
                      _addTicket();
                    },
                    child: const Text(
                      'Add Ticket',
                      style: TextStyle(
                        fontSize: 13,
                        fontWeight: FontWeight.w600,
                        color: Colors.white,
                      ),
                    )),
              ),
            ),
          ),
        ],
      ),
    );
  }

  Widget segmentView() {
    return Container(
      width: double.infinity,
      height: 40,
      color: Colors.white,
      child: SizedBox(
        height: 40,
        child: Padding(
          padding: const EdgeInsets.only(left: 10, right: 10),
          child: DlSegment(
            segments: {
              '1pm': '1PM',
              '6pm': '6PM',
              '8pm': '8PM',
            },
            sliderColor: HexColor('#ff3433'),
            onSegmentChange: (index, value) => {
              debugPrint('value---$value,index---$index'),
              _onTabChanged(index),
            },
          ),
        ),
      ),
    );
  }

  Widget DateView(Map dateMap, int index) {
    var week = dateMap['month'];
    var day = dateMap['day'];
    Color bgColor = index == _currentDayIndex
        ? DL_Config.DL_MainColor
        : HexColor('#eeeeee');
    Color titleColor = index == _currentDayIndex ? Colors.white : Colors.black;
    return GestureDetector(
      onTap: () {
        debugPrint('change day');
        _drawDateClick(index);
      },
      child: Container(
        width: 46,
        margin: const EdgeInsets.fromLTRB(5, 10, 5, 10),
        decoration: BoxDecoration(
            color: bgColor,
            borderRadius: const BorderRadius.all(Radius.circular(10))),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Padding(
              padding: const EdgeInsets.only(top: 3),
              child: Text(
                week,
                style: TextStyle(fontSize: 10, color: titleColor),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(bottom: 0),
              child: Text(
                day,
                style: TextStyle(
                    fontSize: 12,
                    fontWeight: FontWeight.w600,
                    color: titleColor),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget assetTagView() {
    return Container(
      alignment: Alignment.center,
      height: double.infinity,
      width: 30,
      decoration: const BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.only(
            topRight: Radius.circular(10),
            bottomRight: Radius.circular(10),
          )),
      child: Image.asset(
        'assets/sys_imgs/EJ_union.png',
        width: 8.0,
        height: 13.0,
      ),
    );
  }

  Widget ListHeaderText() {
    return Container(
      padding: const EdgeInsets.only(left: 10),
      height: 50,
      alignment: Alignment.centerLeft,
      child: const Text(
        'My Tickets',
        style: TextStyle(
          fontSize: 13,
          fontWeight: FontWeight.w600,
          color: Colors.black,
        ),
      ),
    );
  }

  Widget ListFooterText() {
    return Container(
      padding: const EdgeInsets.only(left: 10, right: 10),
      margin: const EdgeInsets.only(bottom: 15),
      alignment: Alignment.centerLeft,
      child: Text(
        'Please remember tickets displayed on this page are not valid entries into a lottery draw. Any winning amounts shown can only be claimed if you purchased a ticket with the same numbers for the same draw date.',
        style: TextStyle(
          fontSize: 12,
          fontWeight: FontWeight.w400,
          color: HexColor('#999999'),
        ),
      ),
    );
  }
}
